package cn.cdeden.knowledge.controller.online.search;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.TeamRelevanceRole;
import cn.cdeden.knowledge.domain.dto.FileUserDto;
import cn.cdeden.knowledge.domain.dto.FilesTree;
import cn.cdeden.knowledge.domain.dto.PortalQueryParam;
import cn.cdeden.knowledge.domain.dto.SearchFilesInfoDto;
import cn.cdeden.knowledge.domain.vo.FileAnalysisDataVo;
import cn.cdeden.knowledge.enums.TeamParamEnum;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.service.TeamFilesTreeService;
import cn.cdeden.knowledge.service.TeamRelevanceRoleService;
import cn.cdeden.knowledge.service.TeamService;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.system.api.model.LoginUser;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName : ecm_svn
 * @Package : com.cdyd.ecm.modules.online.factory.search
 * @ClassName : SearchFilesInfoPersonal
 * @Author : Chen
 * @Description : // TODO
 * @Date : 2024/4/24 15:56
 * @Version : 1.0
 */

@Slf4j
@RequiredArgsConstructor
@Component("SearchFiles_team")
public class SearchFilesInfoTeam extends SearchFilesInfo {


    private final TeamRelevanceRoleService teamRelevanceRoleService;

    private final TeamFilesTreeService service;

    private final TeamService teamService;

    @Override
    public TableDataInfo<FilesTree> searchInfo(SearchFilesInfoDto infoDto, Pageable pageable) {
        LoginUser user = LoginHelper.getLoginUser();
        List<TeamRelevanceRole> relevanceRole = teamRelevanceRoleService.getRelevanceRole(infoDto.getTeamId(), user.getUserId(), null);
        if (relevanceRole.size() == 0){
            TableDataInfo<FilesTree> filesTreePageInfo = new TableDataInfo<>();
            filesTreePageInfo.setRows(null);
            filesTreePageInfo.setPageSize(pageable.getPageSize());
            filesTreePageInfo.setPage(pageable.getPageNumber());
            filesTreePageInfo.setTotal(0);
            return filesTreePageInfo;
        }else {
            return service.SearchTeamFileTreePage(infoDto,relevanceRole, pageable);
        }
    }

    @Override
    public TableDataInfo<FilesTree> queryNodeFileInfoPage(PortalQueryParam query, LoginUser userDto, Pageable pageable) {
        checkParam(query, userDto);

        IPage queryPage = PageUtil.toMybatisPage(pageable);

        LambdaQueryChainWrapper<TeamFilesTree> wrapper = getWrapper(query, userDto);
        if (ObjectUtils.isEmpty(wrapper)){
            return TableDataInfo.build(queryPage);
        }

        IPage<TeamFilesTree> page = wrapper.page(queryPage);
        TableDataInfo<FilesTree> info = MapstructUtils.convertTableDataInfo(TableDataInfo.build(page),FilesTree.class );
        for (FilesTree tree : info.getRows()) {
            tree.setLibraryType(TreeEnum.TEAM.getType());
        }
        return info;
    }

    @Override
    public List<FilesTree> queryNodeFileInfo(PortalQueryParam query, LoginUser userDto) {
        checkParam(query, userDto);
        LambdaQueryChainWrapper<TeamFilesTree> wrapper = getWrapper(query, userDto);
        if (ObjectUtils.isEmpty(wrapper)){
            return new ArrayList<>();
        }
        List<TeamFilesTree> list = wrapper.orderByAsc(TeamFilesTree::getParentId,TeamFilesTree::getCreateTime).list();
        List<FilesTree> filesTrees = MapstructUtils.convert(list, FilesTree.class);

        for (FilesTree tree : filesTrees) {
            tree.setLibraryType(TreeEnum.TEAM.getType());
        }
        return filesTrees;
    }

    @Override
    public List<FileAnalysisDataVo> getNewFileAnalysisData(Map<String, List<String>> resultMap) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<FileAnalysisDataVo> fileAnalysisDataVos = new ArrayList<>();
        resultMap.forEach( (k,v) -> {
            List<TeamFilesTree> list = service.list(new LambdaQueryWrapper<TeamFilesTree>()
                .eq(TeamFilesTree::getCreateId, loginUser.getUserId().toString())
                .in(TeamFilesTree::getSuffix, v));
            FileAnalysisDataVo fileAnalysisDataVo = new FileAnalysisDataVo();
            fileAnalysisDataVo.setFileSize(list.size());
            fileAnalysisDataVo.setTypeName(k);
            fileAnalysisDataVos.add(fileAnalysisDataVo);
        });
        return fileAnalysisDataVos;
    }


    private  LambdaQueryChainWrapper<TeamFilesTree> getWrapper(PortalQueryParam query, LoginUser userDto) {

        String teamId = query.getTeamId();
        Team byId = teamService.getById(teamId);
        String headNodeId = byId.getHeadNodeId();

        LambdaQueryChainWrapper<TeamFilesTree> wrapper = service.lambdaQuery()
                .eq(TeamFilesTree::getTeamId, teamId);
        List<String> nodeIdList = query.getNodeId(); //是否查询某个节点

//         longList = new ArrayList<>();

        if (CollectionUtils.isEmpty(nodeIdList)) {
            nodeIdList = Arrays.asList(headNodeId);
        }


        //需要验证是否是这个团队的文件夹
        service.selectByNodeIdIsOwn(nodeIdList, teamId,false);
//            查询节点下的全部文件夹信息
        List<TeamFilesTree> filesTrees = service.selectJuniorAll(nodeIdList, "1");
        if (CollectionUtils.isEmpty(filesTrees)){
            return null;
        }
        //查询节点下的全部文件信息
        List<String> longList = filesTrees.stream().filter(tree -> StringUtils.equals(TreeTypeEnum.FILE.getType(), tree.getType()))
                .map(m -> String.valueOf(m.getId()))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(longList)){
            return null;
        }

        //过滤文件
        List<FilesTree> filesTrees01 = teamRelevanceRoleService.checkPermissionByIds(teamId, longList, userDto.getUserId(), TeamParamEnum.CHECK.getParam());

        if (CollectionUtils.isEmpty(filesTrees01)) {
            return null;
        }
        longList = filesTrees01.stream().filter(tree -> StringUtils.equals(TreeTypeEnum.FILE.getType(), tree.getType())).map(m -> String.valueOf(m.getId())).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(longList)){
            return null;
        }

        //查询的文件
        wrapper.in(TeamFilesTree::getId, longList);


        //时间的判断
        if (ObjectUtil.isNotEmpty(query.getStartDate())) {
            wrapper.ge(TeamFilesTree::getCreateTime, query.getStartDate())
                    .le(TeamFilesTree::getCreateTime, query.getEndDate());
        }
        //人员范围
        List<String> userId = query.getUserId();
        if (CollectionUtils.isNotEmpty(userId)){
            wrapper.in(TeamFilesTree::getCreateId, userId);
        }


        wrapper.orderByAsc(TeamFilesTree::getParentId,TeamFilesTree::getCreateTime);
        return wrapper;
    }






    //参数验证
    private void checkParam(PortalQueryParam query,LoginUser userDto) {
        if (StringUtils.isBlank(query.getTeamId())) {
            throw new RuntimeException("团队编号不可以为空参数错误");
        }
//        验证是否这个团队的 或是否有更高级的高级权限
//        权限验证暂时不写
//        if (){
//
//        }


    }
}
